var currDeviceId = "";
var currUnitId = "";
var mutiSelectData = [];
var uMap = new Map();
layui.use(['element','table','form','layer','laydate'], function(){
    var table = layui.table,
        form = layui.form,
        $ = layui.jquery,
        laydate = layui.laydate,
        layer = layui.layer;
    var timeTemplate = xmSelect.render({
        el: '#timeTemplate',
        toolbar: {show: true},
        name: 'timeTemplate',
        //layVerify: 'required',
        //layVerType: '请选择时间模板',
        data: []
    });
    var timeTemplate2 = xmSelect.render({
        el: '#timeTemplate2',
        toolbar: {show: true},
        name: 'timeTemplate',
        //layVerify: 'required',
        //layVerType: '请选择时间模板',
        data: []
    });

    function listTimeTemplates(){
        $.get('/zxkTimeTemplate/listAll', {deviceId:currDeviceId}, function (result) {
            if(result != null){
                mutiSelectData = [];
                if(result.data != null){
                    $.each(result.data, function (index, item) {
                        var obj = {name:item.name,value:item.id,selected:false};
                        mutiSelectData.push(obj);
                    });
                    timeTemplate.update({
                        data: mutiSelectData,
                        autoRow: true,
                    });
                    timeTemplate2.update({
                        data: mutiSelectData,
                        autoRow: true,
                    });
                }
            }

        });
    }

    //日期
    laydate.render({
        elem: '#systemTime',
        trigger : 'click',
        type: 'datetime',
        //min: minDate()//设置min默认最小值
    });
    loadCommunityList();

    addUser = function () {
        if(!currDeviceId){
            layer.msg("请选择门禁设备",{icon:5});
            return ;
        }
        listTimeTemplates();
        $("#resource_form")[0].reset();
        $("#upload_form").attr("disabled", false);
        $("#upload_form").attr("class", "layui-btn");
        $('#demo1').removeAttr("src");
        loadUser();
        layer.open({
            type: 1
            , title: '新增人员'
            , area: ['55%', '80%']
            , content: $('#uploadDiv')
        });
    };
    function loadUser(selected){
        $.get('/zxkUser/loadUserList', {unitId:currUnitId}, function (result) {
            if(result != null){
                if(result.data != null){
                    var $opt_html = "<option value=''>请选择</option>";
                    $.each(result.data, function (index, item) {
                        $opt_html += "<option value='" + item.id + "'>" + item.name + "</option>";
                        if(!uMap.has(item.id)){
                            uMap.set(item.id,item);
                        }
                    });
                    $("#name").empty().append($opt_html);
                    if(selected){
                        $("#name").val(selected);
                    }
                    form.render('select');
                }
            }

        });
    }
    $("#uploadBtn").on("click",function(){
        $("#uploadImg").click();
    });

    $("#uploadImg").on("change",function(){
        var filePath = $(this).val();
        if(filePath.toLowerCase().indexOf("jpg") !== -1 ) {
            var fr = new FileReader();//创建new FileReader()对象
            //判断图片大小
            var filesize = $(this)[0].files[0];
            if(filesize.size > 0){
                if(filesize.size < 1024*20 || filesize.size > 1024*768){
                    layer.msg('请上传20~768K的人脸图片');
                    return false;
                }
            }
            fr.onload = function(e) {
                $('#demo1').attr('src', e.target.result);
                $('#userFaceInfo').val(e.target.result);
            }
            var imgObj = this.files[0];//获取图片
            fr.readAsDataURL(imgObj);//将图片读取为DataURL

        } else {
            layer.msg("请上传20~768Kkb的jpg格式的文件！",{icon:5});
            return false
        }
    });
    function loadCommunityList() {
        $.get('/zxkDevice/loadCommunityList', {}, function (result) {
            if(result != null){
                if(result.data != null){
                    var $opt_html = "";
                    $.each(result.data, function (index, item) {
                        $opt_html += "<option value='" + item.communityId + "'>" + item.communityName + "</option>";
                    });
                    $("#communityId").empty().append($opt_html);
                    form.render('select');
                    loadDeviceList($("#communityId").val());
                }
            }

        });
    }

    function formatTime(data){
        return data ? data.replace("T", " "):"";
    }

    form.on('select(userName)',function (data) {
        var sInfo = uMap.get(data.value);
        if(sInfo){
            $("#phone").val(sInfo.phone);
            if(sInfo.certificateNum){
                $("#certificateType").val("0");//身份证
                $("#certificateNum").val(sInfo.certificateNum);
            }
            if(sInfo.faceData !== null && sInfo.faceData !== "" ){
                $("#userFaceInfo").val(sInfo.faceData);
                $('#demo1').attr('src', sInfo.faceData);
            }
            form.render();
        }
    });

    form.on('select(communityId)',function (data) {
        currDeviceId = "";
        loadDeviceList(data.value);
    });
    form.on('select(personType)',function (data) {
        if("13" === data.value){ // 访客
            $("#personCode").val("FK"+new Date().getTime());
        }else if("11" === data.value || "12" === data.value){ // 业主
            $("#personCode").val("YG"+new Date().getTime());
        }else {
            $("#personCode").val("QT"+new Date().getTime());
        }
    });

    function loadDeviceList(val){
        $.get('/zxkUser/listDeviceNames', {communityId:val}, function (res) {
            if (res.status === 200) {
                let data = res.data;
                let str = '';
                for (let i = 0; i < data.length; i++) {
                    var id = data[i].ID;
                    var name = data[i].DEVICENAME;
                    var unitId = data[i].UNITID;
                    if (i === 0) {
                        currDeviceId = id;
                        currUnitId = unitId;
                        str += '<div style="background-color: #f1f1f1" data-id="' + unitId + '" onclick="changeUnit(this)" id="' + id + '" class="floor-item"><div class="floor-item-text">' + name + '</div></div>'
                    } else {
                        str += '<div onclick="changeUnit(this)" data-id="' + unitId + '" id="' + id + '" class="floor-item"><div class="floor-item-text">' + name + '</div></div>'
                    }
                }
                loadUserTable(currDeviceId);
                layui.$('.floor-group').html(str)
            }

        });
    }
    function loadUserTable(deviceId) {
        table.render({
            elem: '#userTable'
            ,url:'/zxkUser/list'
            ,title: '人员管理'
            ,where: {'deviceId': deviceId}
            ,cols: [[
                {field: 'xh',type:'numbers', title: '序号',}
                ,{field:'personCode', title:'编号',align:'center'}
                ,{field:'personType', title:'类型',align:'center',templet:function (data) {
                        return parseType(data.personType);
                    }}
                ,{field:'name', title:'姓名',align:'center'}
                ,{field:'certificateType', title:'证件类型',align:'center',templet:function (data) {
                        return parseCerType(data.certificateType);
                    }}
                ,{field:'certificateNum', title:'证件号',align:'center'}
                ,{field:'phone', title:'手机号',align:'center'}
                ,{field:'faceData', title:'人脸图',align:'center',templet:function (d) {
                        if (d.faceData) {
                            return '<img onclick="magnifyPic(this)" style="cursor: pointer" width="30" height="25" src="' + d.faceData + '"/>';
                        }
                        return "";
                    }}
                ,{field:'createTime', title:'创建时间',  sort: true,templet:
                        function(data){
                            return formatTime(data.createTime);
                        }}
                ,{field:'createUserName', title:'创建人员',align:'center'}
                ,{field:'right',title:'操作',toolbar:'#barOperate',align:'center',width:220}
            ]]
            ,page: true
        });
    }

    table.on('tool(userTable)',function (obj) {
        var data = obj.data;
        switch (obj.event) {
            case 'edit':
                listTimeTemplates();
                $.get('/zxkUser/loadTemplatesByUser',{id:data.id},function (res) {
                    if(res){
                        var templates = res.data;
                        var sData = [];
                        for(var i=0;i<mutiSelectData.length;i++){
                            var id = mutiSelectData[i].value;
                            var name = mutiSelectData[i].name;
                            var selected = mutiSelectData[i].selected;
                            for(var j=0;j<templates.length;j++){
                                if(id === templates[j].timeTemplateId){
                                    selected = true;
                                    break;
                                }
                            }
                            var obj = {name:name,value:id,selected:selected};
                            sData.push(obj);
                        }
                        timeTemplate.update({
                            data: sData,
                            autoRow: true
                        });
                        $("#update_form").attr("disabled", false);
                        $("#update_form").attr("class", "layui-btn");
                        $("#id").val(data.id);
                        // $("#name").val(data.name);
                        loadUser(data.nameId);
                        $("#phone").val(data.phone);
                        $("#certificateType").val(data.certificateType);
                        $("#certificateNum").val(data.certificateNum);
                        $("#personType").val(data.personType);
                        $("#personCode").val(data.personCode);
                        $("#mark").val(data.mark);
                        if(data.faceData === null || data.faceData==="" ){
                            $('#demo1').removeAttr("src");
                        }else {
                            $("#userFaceInfo").val(data.faceData);
                            $('#demo1').attr('src', data.faceData);
                        }
                        form.render();
                        layer.open({
                            type: 1
                            , title: '编辑人员'
                            , area: ['55%', '80%']
                            , content: $('#uploadDiv')
                        });
                    }
                });
                break;
            case 'delete':
                layer.confirm('确定要删除吗?', {
                }, function(){
                    layer.load();
                    $.get('/zxkUser/delete',{id:data.id,deviceId:currDeviceId,type:data.personType},function (res) {
                        layer.msg(res.msg,{
                            time:500,
                            end:function () {
                                table.reload('userTable');
                                layer.closeAll();
                            }
                        });
                    });
                });
                break;

        }
    });

    form.on('submit(query_user)',function () {
        var phone = $("#searcheKey").val();
        var name = $("#searcheName").val();
        if(!currDeviceId){
            table.reload('userTable',[]);
            return false;
        }
        table.reload('userTable',{
            where: {phone:phone,deviceId:currDeviceId,name:name}
            ,page:  {
                curr:1
            }
        });
        return false;
    });

    form.on('submit(upload_form)',function(data){
        $("#upload_form").attr("disabled", true);
        $("#upload_form").attr("class", "layui-btn layui-btn-disabled");
        data.field.communityId = $("#communityId").val();
        data.field.deviceId = currDeviceId;
        var timeTemplates = timeTemplate.getValue();
        var temArr = [];
        for(var i in timeTemplates){
            var obj = {"id":timeTemplates[i].value,"name":timeTemplates[i].name};
            temArr.push(obj);
        }
        data.field.name = $("#name").find("option:selected").text();
        data.field.timeTemplate = JSON.stringify(temArr);
        layer.load();
        $.ajax({
            type: 'post',
            url: '/zxkUser/saveOrUpdate',
            contentType: "application/json;charset=utf-8",
            dataType: 'json',
            data: JSON.stringify(data.field),
            success: function (res) {
                layer.msg(res.msg);
                setTimeout(function (){
                    layer.closeAll();
                },1000);
                $("#upload_form").attr("disabled", false);
                $("#upload_form").attr("class", "layui-btn");
                table.reload('userTable');
            },
        });
        return false;
    });

    $("#cancel_form").on('click',function (){
        layer.closeAll();
        return false;
    });
    // 人员批量下发
    $("#updateData").on("click", function (){
        if(!currDeviceId){
            layer.msg("请选择门禁设备",{icon:5});
            return ;
        }
        listTimeTemplates();
        layer.open({
            type: 1,
            title:"人员批量下发",
            area: ['500px', '260px'],
            content: $('#addUserBatchDiv')
        });
    });
    $("#cancelUserBatch").on("click", function (){
        layer.closeAll();
    });
    form.on('submit(updateData)',function(data){
        layer.confirm('批量下发一个单元的人员数据可能耗时较长，是否继续?', {
        }, function(){
            $("#addUserBatch").attr("disabled", true);
            $("#addUserBatch").attr("class", "layui-btn layui-btn-disabled");
            data.field.communityId = $("#communityId").val();
            data.field.deviceId = currDeviceId;
            var timeTemplates = timeTemplate2.getValue();
            var temArr = [];
            for(var i in timeTemplates){
                var obj = {"id":timeTemplates[i].value,"name":timeTemplates[i].name};
                temArr.push(obj);
            }
            data.field.timeTemplate = JSON.stringify(temArr);
            data.field.unitId = currUnitId;
            layer.load();
            $.ajax({
                type: 'post',
                url: '/zxkUser/saveBatch',
                contentType: "application/json;charset=utf-8",
                dataType: 'json',
                data: JSON.stringify(data.field),
                success: function (res) {
                    layer.msg(res.msg);
                    setTimeout(function (){
                        layer.closeAll();
                    },1000);
                    $("#addUserBatch").attr("disabled", false);
                    $("#addUserBatch").attr("class", "layui-btn");
                    table.reload('userTable');
                },
            });
        });
        return false;
    });

});

function parseType(type) {
    if(typeof status == "undefined" || status == null){
        return "未知";
    }
    switch (Number(type)) {
        case 11: return '业主';
        case 12: return '家庭成员';
        case 13: return '租客';
        default: return "其他";
    }
}
function parseCerType(type) {
    if(typeof status == "undefined" || status == null){
        return "未知";
    }
    switch (type) {
        case 0 : return "身份证";
        case 1 : return "IC卡";
        default: return "其他";
    }
}

function reload(){
    location.reload();
}

function changeUnit(e) {
    var phone = $("#searcheKey").val();
    var name = $("#searcheName").val();
    currDeviceId = layui.$(e).attr('id');
    currUnitId = layui.$(e).attr('data-id');
    layui.$('.floor-item').css('background-color', 'transparent')
    layui.$(e).css('background-color', '#f1f1f1')
    layui.table.reload('userTable', {
        page: {
            curr: 1 //重新从第 1 页开始
        },
        where: {'deviceId': layui.$(e).attr('id'),'phone':phone,'name':name}
    });
}
function magnifyPic(ele) {
    var width = $(ele).width();
    var height = $(ele).height();
    var scaleWH = width/height;
    var bigH = 450;
    var bigW = scaleWH*bigH;
    if(bigW>600){
        bigW = 600;
        bigH = bigW/scaleWH;
    }
    // 放大预览图片
    layer.open({
        type: 1,
        title: false,
        closeBtn: 1,
        shadeClose: true,
        area: [bigW + 'px', bigH + 'px'], //宽高
        content: "<img width='"+bigW+"' height='"+bigH+"' src=" + $(ele).attr("src") + " />"
    });
}
